package cn.lzc.jl.service.util.codec;

import java.nio.charset.Charset;

import org.apache.tomcat.util.codec.binary.Base64;

public class DesUtil
{
    
    /**
     * 加密
     * @param srcStr
     * @param charset
     * @param sKey
     * @return
     */
    public static String encrypt(String srcStr, Charset charset, String sKey)
    {
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = DES3Helper.encrypt(src, sKey);
        return Base64.encodeBase64String(buf);// Des3.parseByte2HexStr(buf);
    }
    
    /**
     * 解密
     *
     * @param hexStr
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String hexStr, Charset charset, String sKey)
        throws Exception
    {
        byte[] src = Base64.decodeBase64(hexStr);//Des3.parseHexStr2Byte(hexStr);
        byte[] buf = DES3Helper.decrypt(src, sKey);
        return new String(buf, charset);
    }
    
    private static final String SKEY = "12345678";
    
    private static final Charset CHARSET = Charset.forName("UTF-8");
    
    public static void main(String[] args)
    {
        // 待加密内容
        String str = "测试内容，今天周四";
        String encryptResult = DesUtil.encrypt(str, CHARSET, SKEY);
        System.out.println(encryptResult);
        // 直接将如上内容解密
        String decryResult = "";
        try
        {
            decryResult = DesUtil.decrypt(encryptResult, CHARSET, SKEY);
        }
        catch (Exception e1)
        {
            e1.printStackTrace();
        }
        System.out.println(decryResult);
    }
}